#!/usr/bin/env python
__rev_id__ = """$Id: xls2csv.py,v 1.1 2005/10/26 07:44:24 rvk Exp $"""
from pyExcelerator import *
import sys

def importCVS(filename):
    cvs = filename.split(".")[0]+'.cvs'
    exec("cvs=unicode(u'%s')")%cvs
    cvs = open(cvs,'wr')
    
    
    if filename:
        for sheet_name, values in parse_xls(filename, 'cp1251'):
            matrix = [[]]
            hseet = 'Sheet = "%s"\n' % sheet_name.encode('cp866', 'backslashreplace')
            cvs.write(hseet)
            cvs.write('----------------\n')
            for row_idx, col_idx in sorted(values.keys()):
                v = values[(row_idx, col_idx)]
                if isinstance(v, unicode):
                    v = v.encode('cp866', 'backslashreplace')
                else:
                    v = `v`
                v = '"%s"' % v.strip()
                last_row, last_col = len(matrix), len(matrix[-1])
                while last_row <= row_idx:
                    matrix.extend([[]])
                    last_row = len(matrix)

                while last_col < col_idx:
                    matrix[-1].extend([''])
                    last_col = len(matrix[-1])

                matrix[-1].extend([v])
                        
            for row in matrix:
                csv_row = ', '.join(row)
                cvs.write(csv_row+'\n')
                    

    else:
        print "error archivo no encontrado"
    
    cvs.close()